package com.sjm.suchbear.sockettest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class MainActivity extends Activity implements View.OnClickListener {

    private TextView btnServer;
    private TextView btnClient;

    private Socket mClient;
    private ServerSocket mServer;
    private Bitmap mBitmap;
    private String toastStr;

    private static String TAG = "tcp socket test";

    private Handler mHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                ((ImageView) findViewById(R.id.image)).setImageBitmap(mBitmap);
            }else if(msg.what == 0x124){
                Toast.makeText(getBaseContext(), toastStr, Toast.LENGTH_SHORT).show();
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnServer = findViewById(R.id.server);
        btnClient = findViewById(R.id.client);
        btnServer.setOnClickListener(this);
        btnClient.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.server) {
            Log.d(TAG, "server button is click ....");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Socket socket = new Socket("192.168.4.1", 4321);
                        toastStr = "IP地址:192.168.4.1 已连接";
                        mHander.sendEmptyMessage(0x124);
                        while (true){
                            if (socket.isConnected()) {
                                InputStream inputStream = socket.getInputStream();
                                //ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                                byte[] data = new byte[30*1024];
                                // 从InputStream当中读取客户端所发送的数据
                                int len = 0;
                                while ((len=inputStream.read(data)) != -1) {
                                    //outStream.write(data, 0, len);
                                    for(int i=0;i<len-1;i++){
                                        if(data[i]==0xff && data[i+1]==0xd8){
                                            toastStr = "找到图片头!!";
                                            mHander.sendEmptyMessage(0x124);
                                        }
                                    }

                                }
                                inputStream.close();
                            }
                        }
                    } catch (ConnectException connectE){
                        toastStr = "IP地址连接失败";
                        mHander.sendEmptyMessage(0x124);
                        connectE.printStackTrace();
                    }catch (Exception e) {
                        toastStr = getExceptionToString(e);
                        mHander.sendEmptyMessage(0x124);
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mClient = new Socket("192.168.4.1", 4321);
                        Log.d(TAG, "connected ...");
                        OutputStream out = mClient.getOutputStream();
                        DataOutputStream dout = new DataOutputStream(out);
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(mClient.getInputStream()));
                        String cmd;
                        Bitmap bitmap = null;
                        Bitmap bitmap1 = null;
                        boolean flag = true;
                        while (true) {
                            cmd = bufferedReader.readLine();
                            Log.d(TAG, "client cmd = " + cmd);
                            if ("read".equals(cmd)) {
                                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                                if (flag) {
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bout);
                                } else {
                                    bitmap1.compress(Bitmap.CompressFormat.JPEG, 20, bout);
                                }
                                bout.flush();
                                Log.d(TAG, "send cap jpg ...bout.size() = " + bout.size());
                                int size = bout.size();
                                String header = String.format("start-%08d", size);
                                Log.d(TAG, "header = " + header + " size = " + header.getBytes().length);
                                dout.write(header.getBytes());
                                dout.write(bout.toByteArray());
                                dout.flush();
                                flag = !flag;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    public static String getExceptionToString(Throwable e) {
        if (e == null){
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }


    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
}
